package com.chery.media.ui.main.home

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.core.view.isVisible
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import coil.load
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.Utils
import com.chery.media.R
import com.chery.media.contacts.RouterContacts
import com.chery.media.contacts.StorageContacts
import com.chery.media.databinding.FragmentMainHomeBinding
import com.chery.media.library.base.BaseVMFragment
import com.chery.media.library.contacts.PathContacts
import com.chery.media.library.download.DownLoadManager
import com.chery.media.library.download.DownloadResultState
import com.chery.media.library.download.downLoadExt
import com.chery.media.library.extend.dp
import com.chery.media.library.extend.navigation
import com.chery.media.library.extend.setNbOnItemClickListener
import com.chery.media.library.extend.shape
import com.chery.media.library.extend.storageData
import com.chery.media.library.extend.toColorInt
import com.chery.media.library.extend.toJson
import com.chery.media.library.extend.toResString
import com.chery.media.library.extend.toast
import com.chery.media.network.model.AppInfoBean
import com.chery.media.network.model.BannerDataBean
import com.chery.media.ui.main.AppAdapter
import com.chery.media.ui.main.HomeBannerAdapter
import com.chery.media.ui.main.MainActivity
import com.chery.media.ui.mediaViewModel
import com.chery.media.ui.music.MusicFloatWindow
import com.youth.banner.config.IndicatorConfig
import com.youth.banner.indicator.RectangleIndicator
import kotlinx.coroutines.launch

class HomeFragment(val appInstall: ArrayList<AppInfoBean> = arrayListOf()) :
    BaseVMFragment<HomeViewModel, FragmentMainHomeBinding>() {

    private val appAdapter by lazy {
        AppAdapter().apply {
            setNbOnItemClickListener { adapter, view, position ->
                val item = getItem(position)
                if (item.appName == R.string.setting.toResString()) {
                    RouterContacts.APP_SET.navigation()
                } else if (item.appName == R.string.music.toResString()) {
//                    RouterContacts.APP_MUSIC.navigation()
                    RouterContacts.APP_MUSIC_PLAY.navigation()
                } else if ((item.packageName?:"").isNullOrEmpty().not() && AppUtils.isAppInstalled(item.packageName?:"")) {
                    val packageManager = requireActivity().packageManager
                    val intent = packageManager.getLaunchIntentForPackage(item.packageName?:"")
                    startActivity(intent)
                    if (item.packageName == "ru.yandex.yandexmaps") {
                        MusicFloatWindow.showMusic(requireActivity() as MainActivity)
                    }
                } else {
                    "App暂未安装".toast()
                }
            }
        }
    }

    override val layoutId: Int
        get() = R.layout.fragment_main_home


    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        viewModel.appInstall.addAll(appInstall)
//        viewModel.getBannerData()
//        viewModel.getCurrentWeather()
//        viewModel.startGetTime()
        val layoutManager = GridLayoutManager(requireContext(), 4)
        mBinding.appList.adapter = appAdapter
        appAdapter.setList(appInstall)
        setBannerData()
    }

    @SuppressLint("SetTextI18n")
    override fun initObserve() {
        mediaViewModel.currentTime.observe(this) {
            mBinding.timeText.text =  it
        }
        viewModel.currentWeather.observe(this) {
            storageData(StorageContacts.CURRENT_WEATHER, it.toJson())
            mBinding.lineView.isVisible = true
            mBinding.tempText.text = "${(it.main?.feelsLike?:"0.0").split(".")[0]}°"
            mBinding.weatherText.text = "${it.weather?.get(0)?.description}"
            mBinding.weatherIcon.load("https://openweathermap.org/img/w/${it.weather?.get(0)?.icon}.png")
        }
        viewModel.bannerData.observe(this) {
            downloadBanner()
            storageData(StorageContacts.BANNER_DATA, it.toJson())
            mBinding.banner.isVisible = true
            setBannerData()
        }
    }

    private fun setBannerData() {
        mBinding.banner.apply {
            shape(R.color.public_FFFFFF_44.toColorInt(), 5.dp.toFloat())
            val bannerAdapter = HomeBannerAdapter(viewModel.bannerData.value?.records?: arrayListOf())
            setAdapter(bannerAdapter)
            indicator = RectangleIndicator(Utils.getApp())
            setIndicatorGravity(IndicatorConfig.Direction.CENTER)
            setOnBannerListener { data, _ ->
                val item = data as BannerDataBean
                when (item.typeId) {
                    "1" -> {
                        openWebPage(item.url)
                    }
                    "2" -> {
                        jumpMaps(item.addr?:"")
                    }
                    "3" -> {
                        RouterContacts.APP_MUSIC.navigation("type" to 2, "musicId" to item.musicId)
                    }
                }
            }
        }
    }

    private var downloadData = MutableLiveData<DownloadResultState>()

    private fun downloadBanner(){
        lifecycleScope.launch {
            viewModel.bannerData.value?.records?.forEach {
                DownLoadManager.downLoad("BANNER_${it.id}", it.image?:"", PathContacts.IMG_DOWNLOAD, "banner_${it.id}.jpg", true, downLoadExt(downloadData))
            }
        }
    }

    private fun openWebPage(url: String?) {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.setData(Uri.parse(url))
        if (intent.resolveActivity(requireActivity().packageManager) != null) {
            startActivity(intent)
        } else {
            "未安装浏览器".toast()
        }
    }


    private fun jumpMaps(address: String) {
        // 创建URI以表示地理位置
//                val uri = Uri.parse("geo:${item.latitude},${item.longitude}")
        val uri = Uri.parse("geo:${address}")
//                val uri = Uri.parse("https://maps.google.com/maps?q=${item.latitude},${item.longitude}")
        val intent = Intent(Intent.ACTION_VIEW, uri)
        // 设置包名以确保只有Yandex地图响应此意图
        intent.setPackage("ru.yandex.yandexmaps")
        if (intent.resolveActivity(requireActivity().packageManager) != null) {
            startActivity(intent)
            MusicFloatWindow.showMusic(requireActivity() as MainActivity)
        } else {
            // 如果没有，则可以提示用户下载Yandex地图或进行其他处理
            "Yandex地图未安装，请安装后重试".toast()
        }
    }

    companion object {
        fun newInstance(installApp: ArrayList<AppInfoBean> = arrayListOf()) = HomeFragment(installApp)
    }

}